from twisted.words.protocols.jabber import client, jid
from twisted.words.xish import domish, xmlstream
from twisted.internet import reactor
import re,threading
import sys, getpass

t = None

name = None
server = None
resource = None
password = None
me = None

thexmlstream = None
tryandregister = 1
daft = None


def initOnline(xmlstream):
	global factory
	print 'Initializing...'
	xmlstream.addObserver('/message', gotMessage)
	xmlstream.addObserver('/*', gotSomething)

def authd(xmlstream):
	global thexmlstream
	thexmlstream = xmlstream
	print "we've authd!"
	print repr(xmlstream)

	#need to send presence so clients know we're
	#actually online
	presence = domish.Element(('jabber:client', 'presence'))
	presence.addElement('status').addContent('Available')
	xmlstream.send(presence)

	initOnline(xmlstream)

def send(author, to, msg):
	global thexmlstream
	message = domish.Element(('jabber:client','message'))
	message["to"] = jid.JID(to).full()
	message["from"] = jid.JID(author).full()
	message["type"] = "chat"
	message.addElement("body", "jabber:client", msg)
	
	thexmlstream.send(message)

def gotMessage(el):
	global me
	global daft
	#print 'Got message: %s' % str(el.attributes)
	from_id = el["from"]
	if el["type"] == "error":
		pass
	
	body = "empty"
	for e in el.elements():
		if e.name == "body":
			body = unicode(e.__str__())
			break
	if body != "empty":
		print "\n"+from_id+": "+body+"\n"
		daft.boom(body,from_id,"xmpp")

def addfriend(user):
	global thexmlstream
	presence = domish.Element(('jabber:client', 'presence'))
	presence['to'] = user
	presence['type'] = 'subscribed'
	thexmlstream.send(presence)
	print 'Sent something: %s -> %s' % (presence.name, str(presence.attributes))
	presence = domish.Element(('jabber:client', 'presence'))
	presence['to'] = user
	presence['type'] = 'subscribe'
	thexmlstream.send(presence)
	print 'Sent something: %s -> %s' % (presence.name, str(presence.attributes))

def removefriend(user):
	global thexmlstream
	presence = domish.Element(('jabber:client', 'presence'))
	presence['to'] = user
	presence['type'] = 'unsubscribed'
	thexmlstream.send(presence)
	print 'Sent something: %s -> %s' % (presence.name, str(presence.attributes))
	presence = domish.Element(('jabber:client', 'presence'))
	presence['to'] = user
	presence['type'] = 'unsubscribe'
	thexmlstream.send(presence)
	print 'Sent something: %s -> %s' % (presence.name, str(presence.attributes))

def gotSomething(el):
	global thexmlstream
	print 'Got something: %s -> %s' % (el.name, str(el.attributes))
	if el.name != "error":
		if el.getAttribute('type') == 'subscribe':
			print "got a subscription request!" + el['from']
			addfriend(el['from'])
		

		if el.getAttribute('type') == 'unsubscribe':
			print "got an unsubscription request!" + el['from']
			removefriend(el['from'])
		if el.getAttribute('from').find('dobbybot') >= 0 and el.getAttribute('type')=='unavailable':
			presence = domish.Element(('jabber:client', 'presence'))
			thexmlstream.send(presence)	

def authfailedEvent(xmlstream):
	global reactor
	print 'Auth failed!'
	reactor.stop()

def beginXMPP():
	global me

	USER_HANDLE = "dobbybot@jabber.org"
	PASSWORD = "stilllovessocks"
	me = USER_HANDLE + "/TwistedWords"
	myJid = jid.JID(me)
	server = USER_HANDLE[USER_HANDLE.find('@')+1:]

	factory = client.basicClientFactory(myJid, PASSWORD)

	# Register authentication callbacks
	factory.addBootstrap('//event/stream/authd', authd)

	# Go!
	reactor.connectTCP(server, 5222, factory)
	reactor.run()


def tick():
	pass
def say(daft,r,who,w):
	global me
	print "\nME @"+who+": "+r+"\n"
	if "xmpp" in w.split(","):
		send(me, who, r)

class xmppthread( threading.Thread ):
	def __init__(self,daft):
		print "xmpp thread init"
		threading.Thread.__init__(self)
		self.daft = daft
	def run ( self ):
		print "running xmpp thread"
		beginXMPP()

def start(tdaft):
	global daft
	daft = tdaft
	if "xmpp" in sys.argv or "jabber" in sys.argv :
		t = xmppthread(tdaft)
		t.start()
		
	return True
def stop():
	global reactor
	reactor.stop()
	return True
